package com.yc.chatroom.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;

import org.springframework.stereotype.Component;

import com.yc.chatroom.common.dto.*;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

/**
 * 
 * @author yuancan
 * 参考：https://blog.csdn.net/Alexwym/article/details/90047132
 */
@Component
public class ClientManager {
	
	/**
	 * 消息队列（存放所有从服务器端发回的消息）
	 * 因为是客户端，只有一个人，所有的消息都放在一个队列是合适的
	 */
	public LinkedBlockingQueue<ShowMsgDto> MSG_QUEUE = new LinkedBlockingQueue<ShowMsgDto>();
	
	public LoginResponse loginResponse = null;
	
	//通道
	private Channel channel = null;
	
	/**
	 * 连接服务器
	 * @param ip
	 * @param port
	 * @throws IOException
	 */
	public void connect(String ip, int port) throws IOException {
		EventLoopGroup group = new NioEventLoopGroup();
		
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
				.channel(NioSocketChannel.class)
				.option(ChannelOption.TCP_NODELAY, true)
				.handler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					//添加解码器
					ch.pipeline().addLast(new ObjectDecoder(100*100, ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
					ch.pipeline().addLast(new ObjectEncoder());//添加编码器
					
					ch.pipeline().addLast(new ClientHandle(ClientManager.this));//获取外部类对象
				}
				
			});
			
			ChannelFuture channelFuture = b.connect(ip, port).sync();
			channel = channelFuture.channel();
			
			//使客户端一直处于等待关闭的阻塞长连接状态
			channel.closeFuture().sync();
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
	
	/**
	 * 发送消息
	 * @param msg
	 */
	public void sendMsg(BaseDto msg) {
		//判断连接状态
		if (null == channel) {
			new Thread(() -> {
				try {
					connect("localhost", 8787);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}).start();
			
		}
		
		while(null == channel) {
			try {
				System.out.println("连接中...");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		if (null != msg) {
			try {
				System.out.println("---writeAndFlush----");
				channel.writeAndFlush(msg);
				channel.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		
	}
	
	//获取全部用户列表
	

//	public static void main(String[] args) {
//		try {
//			new ClientManager().connect("127.0.0.1", 8080);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//	}
	
//	class

}
